<template>
  <div v-loading="loading" class="state">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px" :class="isCard ? 'meeting-card' : ''" class="dataForm">
      <el-row>
        <el-row style="flex-wrap: wrap;display: flex">
          <el-col v-if="isShowField" :span="12">
            <el-form-item :label="$t('项目名称')" prop="dealId">
              <template>
                <router-link
                  target="_blank"
                  :to="{path:'/deal/home/dealBaseHome',query:{id:form.dealId,companyId:form.companyId}}"
                  class="link_a"
                >{{ form.dealName }} </router-link>
              </template>
            </el-form-item>
          </el-col>
          <el-col v-if="isShowField" :span="12">
            <el-form-item :label="$t('标的公司')" prop="companyId">
              <template>
                <router-link
                  target="_blank"
                  :to="{path:'/company/base/companyBaseHome',query:{companyId:form.companyId}}"
                  class="link_a"
                >{{ form.companyName }}</router-link>
              </template>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('会议日期')" prop="mtDate">
              <el-date-picker
                v-model="form.mtDate"
                clearable
                style="width: 200px"
                type="date"
                value-format="yyyy-MM-dd"
                :placeholder="$t('会议日期')"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('会议时间')" prop="mtTime">
              <el-time-picker
                v-model="mtTime"
                is-range
                range-separator="-"
                format="HH:mm"
                value-format="HH:mm"
                :picker-options="{
                  selectableRange:'00:00 - 23:59'
                }"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                placeholder="会议时间"
                @change="changeTime"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('会议纪要人')" prop="mtMinutesPerson">
              <UserSelect v-model="form.mtMinutesPerson" :placeholder="$t('会议纪要人')" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('常规参会人员')" prop="regularAttendees">
              <UserSelect v-model="form.regularAttendees" multiple :placeholder="$t('常规参会人员')" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('项目组成员')" prop="dealTeamMembers">
              <UserSelect v-model="form.dealTeamMembers" multiple :placeholder="$t('项目组成员')" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('内部其他参会人员')" prop="innerMember">
              <UserSelect v-model="form.innerMember" multiple :placeholder="$t('内部其他参会人员')" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('外部其他参会人员')" prop="outerMember">
              <!--              <el-input v-model="form.outerMember" :placeholder="$t('外部其他参会人员')" />-->
              <div id="inputMultipleBox" class="input-multiple-box">
                <div>
                  <el-tag v-for="(tag, index) in form.outerMember" :key="index" style="margin-right: 5px;" type="info" closable @close="handleClose(index,'person')">
                    {{ tag }}
                  </el-tag>
                </div>
                <el-input
                  v-model="memberValue"
                  style="flex: 1; min-width: 100px"
                  :placeholder="$t('外部其他参会人员(按enter键添加或以多个英文逗号隔开)')"
                  @keyup.enter.native="handleInputConfim($event,'person')"
                  @blur="handleInputConfim($event,'person')"
                />
              </div>
            </el-form-item>
          </el-col>
          <!--          <el-col :span="12">-->
          <!--            <el-form-item :label="$t('外部其他参会邮箱')" prop="outerEmail">-->
          <!--              &lt;!&ndash;              <el-input v-model="form.outerEmail" :placeholder="$t('外部其他参会邮箱')" />&ndash;&gt;-->
          <!--              <div id="inputMultipleBox2" class="input-multiple-box">-->
          <!--                <div>-->
          <!--                  <el-tag v-for="(tag, index) in form.outerEmail" :key="index" style="margin-right: 5px;" type="info" closable @close="handleClose(index,'email')">-->
          <!--                    {{ tag }}-->
          <!--                  </el-tag>-->
          <!--                </div>-->
          <!--                <el-input-->
          <!--                  v-model="emailValue"-->
          <!--                  style="flex: 1; min-width: 100px"-->
          <!--                  :placeholder="$t('外部其他参会邮箱(按enter键添加或以多个英文逗号隔开)')"-->
          <!--                  @keyup.enter.native="handleInputConfim($event,'email')"-->
          <!--                  @blur="handleInputConfim($event,'email')"-->
          <!--                />-->
          <!--              </div>-->
          <!--            </el-form-item>-->
          <!--          </el-col>-->
          <el-col :span="12">
            <el-form-item :label="$t('会议地点')" prop="mtAddress">
              <!--              <el-input v-model="form.mtAddress" :placeholder="$t('会议地点')" />-->
              <el-select
                v-model="form.mtAddress"
                :placeholder="$t('会议地点')"
                clearable
              >
                <el-option
                  v-for="item in meetingRoom"
                  :key="item.id"
                  style="height: auto!important;"
                  :label="item.name"
                  :value="item.id"
                  :disabled="item.delFlag === '1'"
                >
                  <span style="font-size: 14px">{{
                    item.name + (item.mailAddress ? '(' + item.mailAddress + ')' : '')
                  }}</span>
                  <span style="display:block;color:#b4b4b4;font-size: 12px;margin-top: -10px;">{{ item.address }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item :label="$t('会议链接')" prop="meetingInvitation">
              <el-input v-model="form.meetingInvitation" :placeholder="$t('会议链接')" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item :label="$t('主送人员')" prop="sendUser">
              <UserSelect v-model="form.sendUser" multiple :placeholder="$t('主送人员')" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item :label="$t('抄送人员')" prop="ccUser">
              <UserSelect v-model="form.ccUser" multiple :placeholder="$t('抄送人员')" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item v-if="isShowField" :label="$t('申请标题')" prop="actTitle">
              <el-input v-model="form.actTitle" show-word-limit maxlength="200" :placeholder="$t('申请标题')">
                <!--                <template slot="prepend">{{ form.remark + '-' }}</template>-->
              </el-input>
            </el-form-item>
            <el-form-item v-else :label="$t('申请标题')" prop="actTitle">
              <el-input v-model="form.actTitle" show-word-limit maxlength="200" :placeholder="$t('申请标题')" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item :label="$t('申请内容')" prop="applyContent">
              <EditorTxt v-if="!loading" ref="editorTxt" v-model="form.applyContent" :height="400" :placeholder="$t('申请内容')" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-row>
      <FileTable
        :business-id="form.dealId"
        :list.sync="form.fileList"
        data-type="mt_arrange_info"
        :btn-show="!otherBtnHide"
      />
    </el-form>
    <div
      v-if="source !== 'sheet' && viewType !== 'view'"
      slot="footer"
      class="dialog-footer"
      style="text-align: right;"
    >
      <!--保存 取消按钮-->
      <save-btn cancel-show :save-show="form.delFlag === '2' || form.conclusionStatus === 'N' || !form.conclusionStatus" />
    </div>
  </div>
</template>

<script>
import {
  saveMtArrangeInfo,
  getMtArrangeInfo,
  getMtArrangeInfoByMeetingId,
  getMtArrangeInfoByMeetingIds
} from '@/api/meeting/info/mtArrangeInfo'
import EditorTxt from '@/components/Tinymce'
import mixin from '@/views/deal/mt/mixin/mixin'
import { listMtRoom } from '@/api/meeting/room/mtRoom'
    export default {
      components: { EditorTxt },
      mixins: [mixin],
      props: {
        ...mixin
      },
        data() {
            return {
                // 表单参数
                form: {},
                // 遮罩层
                loading: false,
              mtTime: ['', ''],
              otherBtnHide: false,
                // 表单校验
                rules: {
                  mtTime: [{ required: true, message: this.$t('必填信息'), trigger: 'change' }],
                  mtDate: [{ required: true, message: this.$t('必填信息'), trigger: 'change' }],
                  actTitle: [{ required: true, message: this.$t('必填信息'), trigger: 'change' }],
                  applyContent: [
                    { required: true, message: this.$t('必填信息'), trigger: 'change' },
                    { validator: this.validateContent, trigger: 'change' }
                  ]
                },
              memberValue: undefined,
              emailValue: undefined,
              isCard: false,
              viewType: undefined,
              isShowField: true,
              closeFlag: true,
              meetingRoom: [],
              durationOptions: [],
              formOpen: false
            }
        },
        created() {
          listMtRoom({ type: 'all' }).then(res => {
            this.meetingRoom = res.rows
          })
          this.getDicts('mt_duration').then(res => {
            this.durationOptions = res.data
            if (!(this.durationOptions instanceof Array)) {
              this.durationOptions = []
            }
            this.durationOptions.push({
              dictValue: 'custom',
              dictLabel: '选择结束时间'
            })
          })
          this.$bus.$emit('async_meeting_done')
        },
        methods: {
            // 初始化数据
            init(data) {
              this.viewType = data.type
              this.closeFlag = data.closeFlag
              if (this.viewType !== 'view') {
                if (this.$parent.$parent.$parent.$parent.$parent.$parent?.hideProcess) {
                  this.$parent.$parent.$parent.$parent.$parent.$parent.hideProcess(true)
                }
              }

                this.loading = true
                this.isCard = data && data.isCard
                  if (data != null && data.id !== undefined) {
                      getMtArrangeInfo(data.id).then(response => {
                        console.log(response.data, '排会数据')
                        if (response.data.mtTime) {
                            this.mtTime = response.data.mtTime.split('-')
                          } else {
                            var arr = []
                            var date = this.getNextScheduledTime()
                            var startTime = this.parseTime(date, '{h}:{i}')
                            var timeStamp = date.getTime() + (60 * 60 * 1000)
                            var endTime = this.parseTime(new Date(timeStamp), '{h}:{i}')
                            arr.push(startTime)
                            arr.push(endTime)
                            this.mtTime = ['', '']
                            // response.data.mtTime = arr.join('-')
                          }
                          this.isShowField = !response.data.multiple
                          this.form = response.data
                          this.$parent.form = this.form
                          this.loading = false
                      }).catch(() => {
                        this.loading = false
                      })
                  } else if (data && data.meetingId) {
                  getMtArrangeInfoByMeetingId(data.meetingId).then(response => {
                    if (response.data.mtTime) {
                      this.mtTime = response.data.mtTime.split('-')
                    } else {
                      var arr = []
                      var date = this.getNextScheduledTime()
                      var startTime = this.parseTime(date, '{h}:{m}')
                      var timeStamp = date.getTime() + (60 * 60 * 1000)
                      var endTime = this.parseTime(new Date(timeStamp), '{h}:{m}')
                      arr.push(startTime)
                      arr.push(endTime)
                      this.mtTime = ['', '']
                    }
                    if (response.data.dataIds && response.data.dataIds.length !== 0) {
                      this.isShowField = false
                      this.multiple = true
                    } else {
                      this.isShowField = true
                      this.multiple = false
                    }
                    this.form = response.data
                    this.$parent.form = this.form
                    this.loading = false
                  })
                } else {
                    this.reset()
                    this.loading = false
                }
            },
          getNextScheduledTime() {
            // 获取当前时间
            const now = new Date()
            const currentHour = now.getHours()
            const currentMinute = now.getMinutes()

            // 创建一个新的Date对象用于计算下一个半点或整点
            const scheduledTime = new Date(now.getTime())

            // 如果当前分钟小于30，则设置为下一个半点
            if (currentMinute < 30) {
              scheduledTime.setMinutes(30)
              scheduledTime.setSeconds(0)
              scheduledTime.setMilliseconds(0)
            } else {
              // 如果当前分钟大于或等于30，则设置为下一个整点
              scheduledTime.setHours(currentHour + 1)
              scheduledTime.setMinutes(0)
              scheduledTime.setSeconds(0)
              scheduledTime.setMilliseconds(0)
            }

            // const hours = scheduledTime.getHours() < 0 ? '0' + scheduledTime.getHours() : scheduledTime.getHours()
            // const minutes = scheduledTime.getMinutes() < 0 ? '0' + scheduledTime.getMinutes() : scheduledTime.getMinutes()
            //
            // return hours + ':' + minutes
            return scheduledTime
          },
          validateContent(rule, value, cb) {
            var num = this.form.applyContent.length
            try {
              // const text = this.$refs.editorTxt.$el.innerText
              // var temp = text.split('\n')
              // temp = temp[temp.length - 1]
              // num = Number(temp.replace('字', ''))
              num = this.$refs.editorTxt.wordcount
              if (isNaN(Number(num))) {
                num = this.form.applyContent.length
              }
            } catch (e) {
              console.error(e)
              num = this.form.applyContent.length
            }

            if (num > 2000) {
              cb(new Error(this.$t('字数不能超过2000')))
            } else {
              cb()
            }
          },
          batchInit(data, flag) {
            this.closeFlag = flag
            this.loading = true
            this.isShowField = false
            this.form.multiple = true
            var arr = []
            data.forEach(item => {
              arr.push(item.meetingId)
            })
            getMtArrangeInfoByMeetingIds(arr).then(res => {
              console.log(res)
              if (res.data.mtTime) {
                this.mtTime = res.data.mtTime.split('-')
              } else {
                var arr = []
                var date = this.getNextScheduledTime()
                var startTime = this.parseTime(date, '{h}:{i}')
                var timeStamp = date.getTime() + (60 * 60 * 1000)
                var endTime = this.parseTime(new Date(timeStamp), '{h}:{i}')
                arr.push(startTime)
                arr.push(endTime)
                this.mtTime = ['', '']
                // res.data.mtTime = arr.join('-')
              }
              this.form = res.data
              this.$parent.form = this.form
              this.loading = false
            })
          },
          handleInputConfim(value, type) {
              var arr = []
            if (type === 'email' && this.emailValue) {
              arr = this.emailValue.split(',')
              if (!(this.form.outerEmail instanceof Array)) {
                this.form.outerEmail = []
              }
              this.form.outerEmail = this.form.outerEmail.concat(arr)
            } else if (type === 'person' && this.memberValue) {
              arr = this.memberValue.split(',')
              if (!(this.form.outerMember instanceof Array)) {
                this.form.outerMember = []
              }
              this.form.outerMember = this.form.outerMember.concat(arr)
            }
            this.emailValue = ''
            this.memberValue = ''
          },
          handleClose(index, type) {
            if (type === 'email') {
              this.form.outerEmail.splice(index, 1)
            } else {
              this.form.outerMember.splice(index, 1)
            }
          },
            // 表单重置
            reset() {
                this.form = {
                    id: undefined,
                    meetingId: undefined,
                    dealId: undefined,
                    companyId: undefined,
                    mtDate: undefined,
                    mtTime: undefined,
                    mtMinutesPerson: undefined,
                    regularAttendees: undefined,
                    dealTeamMembers: undefined,
                    innerMember: undefined,
                    outerMember: [],
                    outerEmail: undefined,
                    mtAddress: undefined,
                    sendUser: undefined,
                    ccUser: undefined,
                    actTitle: undefined,
                    applyContent: undefined,
                    remark: undefined,
                    createBy: undefined,
                    createTime: undefined,
                    updateBy: undefined,
                    updateTime: undefined,
                    delFlag: undefined,
                  multiple: false,
                  meetingInvitation: undefined,
                  fileList: []
                }
                this.resetForm('form')
            },
            // 取消按钮
            cancel() {
                this.$parent.$parent.formOpen = false
                this.$parent.$parent.reset()
            },
            // 关闭form页面
            closeForm() {
                // 关闭form页面遮罩层
                this.loading = false
                // 关闭form页面
                if (this.$parent.$parent.formOpen !== undefined) {
                  this.$parent.$parent.formOpen = false
                }
                // 刷新list页面
                if (this.$parent.$parent.getList !== undefined) {
                  this.$parent.$parent.getList()
                }
            },
          changeTime() {
            // var arr = []
            // var date = this.getNextScheduledTime()
            // var startTime = this.parseTime(date, '{h}:{i}')
            // var timeStamp = date.getTime() + (60 * 60 * 1000)
            // var endTime = this.parseTime(new Date(timeStamp), '{h}:{i}')
            // arr.push(startTime)
            // arr.push(endTime)
            // this.mtTime = ['', '']
            this.form.mtTime = this.mtTime.join('-')
          },
            /** 提交按钮 */
            submitForm() {
                this.$refs['form'].validate(valid => {
                    if (valid) {
                        this.loading = true
                      if (this.closeFlag === '2') {
                        this.form.closeFlag = '0'
                      }
                        if (this.mtTime.length === 2 && this.mtTime[0] && this.mtTime[1]) {
                          this.form.mtTime = this.mtTime.join('-')
                        }
                        saveMtArrangeInfo(this.form).then(response => {
                            if (response.code === 200) {
                                this.msgSuccess(this.$t('保存成功'))
                                this.closeForm()
                            } else {
                                this.msgError(response.msg)
                            }
                            this.loading = false
                        })
                    } else {
                       this.locationError(document)
                    }
                }).catch(() => {
                    this.loading = false
                })
           }
        }
    }
</script>
<style scoped lang="scss">
/deep/ #inputMultipleBox {
  .el-input__inner {
    border: none
  }
}

/deep/ #inputMultipleBox2 {
  .el-input__inner {
    border: none
  }
}

.input-multiple-box {
  width: 100%;
  border-radius: 4px;
  border: 1px solid #dcdfe6;
  padding: 0 5px;
  display: flex;
  flex-wrap: wrap;
}

/deep/ .dataForm .avatar-uploader {
  display: none;
}
</style>
